package cn.wolfcode.p2p.website.controller;

import cn.wolfcode.p2p.base.domain.LoginInfo;
import cn.wolfcode.p2p.base.domain.UserInfo;
import cn.wolfcode.p2p.base.exception.DisplayableException;
import cn.wolfcode.p2p.base.service.ILoginInfoService;
import cn.wolfcode.p2p.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginInfoController {

    @Autowired
    private ILoginInfoService loginInfoService;

    @ResponseBody
    @RequestMapping("/userRegister")
    public JSONResult register(String username, String verifycode, String password, String confirmPwd){
        JSONResult result;
        try {
            loginInfoService.register(username, verifycode, password, confirmPwd);
            result = new JSONResult("注册成功");
        } catch (DisplayableException ex) {
            //异常需要在前台显示
            ex.printStackTrace();
            result = new JSONResult(false, ex.getMessage());
        } catch (Exception e){
            //异常记录到数据库或日志文件中
            e.printStackTrace();
            result = new JSONResult(false, "系统异常,请联系管理员");
        }
        return result;
    }

    @ResponseBody
    @RequestMapping("/checkPhoneNumber")
    public boolean checkPhoneNumber(String username){
        return loginInfoService.checkPhoneNumber(username);
    }

    @ResponseBody
    @RequestMapping("/userLogin")
    public JSONResult userLogin(String username, String password){
        JSONResult result = null;
        try {
            LoginInfo loginInfo = loginInfoService.userLogin(username, password, LoginInfo.USERTYPE_USER);
            if (loginInfo == null) {
                result = new JSONResult(false, "账号或密码错误");
                return result;
            }
            result = new JSONResult("登录成功");
        } catch (DisplayableException ex) {
            //异常需要在前台显示
            ex.printStackTrace();
            result = new JSONResult(false, ex.getMessage());
        } catch (Exception e){
            //异常记录到数据库或日志文件中
            e.printStackTrace();
            result = new JSONResult(false, "系统异常,请联系管理员");
        }
        return result;
    }
}
